<template>
  <div class="login-log-container">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">登录日志管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport" :loading="exporting">
              导出日志
            </el-button>
            <el-button type="danger" @click="handleClear" :loading="clearing">
              清空日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="登录状态">
          <el-select v-model="queryForm.status" placeholder="请选择登录状态" clearable>
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="queryForm.ipAddress" placeholder="请输入IP地址" clearable />
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="queryForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6">
          <el-card class="statistics-card">
            <div class="statistics-item">
              <div class="statistics-number">{{ statistics.totalCount }}</div>
              <div class="statistics-label">总登录次数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistics-card">
            <div class="statistics-item">
              <div class="statistics-number success">{{ statistics.successCount }}</div>
              <div class="statistics-label">成功登录</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistics-card">
            <div class="statistics-item">
              <div class="statistics-number danger">{{ statistics.failCount }}</div>
              <div class="statistics-label">失败登录</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="statistics-card">
            <div class="statistics-item">
              <div class="statistics-number warning">{{ statistics.todayCount }}</div>
              <div class="statistics-label">今日登录</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 日志列表 -->
      <el-table
        :data="logList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="location" label="登录地点" width="150" />
        <el-table-column prop="browser" label="浏览器" width="120" />
        <el-table-column prop="os" label="操作系统" width="120" />
        <el-table-column prop="status" label="登录状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="logoutTime" label="登出时间" width="180">
          <template #default="{ row }">
            {{ row.logoutTime ? formatDateTime(row.logoutTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="在线时长" width="120">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="message" label="登录信息" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="登录日志详情"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">
          {{ currentLog.username }}
        </el-descriptions-item>
        <el-descriptions-item label="登录状态">
          <el-tag :type="currentLog.status === 1 ? 'success' : 'danger'">
            {{ currentLog.status === 1 ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">
          {{ currentLog.ipAddress }}
        </el-descriptions-item>
        <el-descriptions-item label="登录地点">
          {{ currentLog.location }}
        </el-descriptions-item>
        <el-descriptions-item label="浏览器">
          {{ currentLog.browser }}
        </el-descriptions-item>
        <el-descriptions-item label="操作系统">
          {{ currentLog.os }}
        </el-descriptions-item>
        <el-descriptions-item label="登录时间">
          {{ formatDateTime(currentLog.loginTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="登出时间">
          {{ currentLog.logoutTime ? formatDateTime(currentLog.logoutTime) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="在线时长">
          {{ formatDuration(currentLog.duration) }}
        </el-descriptions-item>
        <el-descriptions-item label="用户代理">
          {{ currentLog.userAgent }}
        </el-descriptions-item>
        <el-descriptions-item label="登录信息" :span="2">
          {{ currentLog.message }}
        </el-descriptions-item>
        <el-descriptions-item label="失败原因" :span="2" v-if="currentLog.failReason">
          <pre class="log-detail-pre error-message">{{ currentLog.failReason }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { showSuccess, showError } from '@/utils/message'
import type { FormInstance } from 'element-plus'
import { getLoginLogList, type LoginLogQueryParams } from '@/api/user'


// 作者：Wu.Liang
// 登录日志管理组件

interface LoginLog {
  id: number
  username: string
  ipAddress: string
  location: string
  browser: string
  os: string
  status: number
  loginTime: string
  logoutTime: string
  duration: number
  message: string
  userAgent: string
  failReason: string
}

const queryForm = reactive({
  username: '',
  status: '',
  ipAddress: '',
  timeRange: []
})

const logList = ref<LoginLog[]>([])
const loading = ref(false)
const exporting = ref(false)
const clearing = ref(false)
const detailVisible = ref(false)
const currentLog = ref<LoginLog>({} as LoginLog)
const selectedLogs = ref<LoginLog[]>([])

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

const statistics = reactive({
  totalCount: 0,
  successCount: 0,
  failCount: 0,
  todayCount: 0
})

// 获取登录日志列表
const fetchLoginLogList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params: LoginLogQueryParams = {
      current: pagination.current,
      size: pagination.size,
      username: queryForm.username || undefined,
      loginStatus: queryForm.status || undefined,
      loginIp: queryForm.ipAddress || undefined,
      startTime: queryForm.timeRange?.[0] || undefined,
      endTime: queryForm.timeRange?.[1] || undefined
    }
    
    // 调用后端API获取登录日志列表
    const response = await getLoginLogList(params)
    
    if (response.data) {
      logList.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取登录日志失败:', error)
    showError('加载登录日志失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const getStatistics = async () => {
  try {
    // TODO: 调用后端API获取统计信息
    // const response = await loginLogApi.getLoginLogStatistics()
    // Object.assign(statistics, response.data)
    
    // 模拟数据
    Object.assign(statistics, {
      totalCount: 1250,
      successCount: 1180,
      failCount: 70,
      todayCount: 25
    })
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  fetchLoginLogList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    username: '',
    status: '',
    ipAddress: '',
    timeRange: []
  })
  pagination.current = 1
  fetchLoginLogList()
}

// 导出日志
const handleExport = async () => {
  try {
    exporting.value = true
    // TODO: 调用后端API导出登录日志
    // await loginLogApi.exportLoginLog(queryForm)
    showSuccess('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    showError('导出失败')
  } finally {
    exporting.value = false
  }
}

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有登录日志吗？此操作不可恢复！', '确认清空', {
      type: 'warning'
    })
    
    clearing.value = true
    // TODO: 调用后端API清空登录日志
    // await loginLogApi.clearLoginLog()
    showSuccess('清空成功')
    fetchLoginLogList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      showError('清空失败')
    }
  } finally {
    clearing.value = false
  }
}

// 查看详情
const handleViewDetail = (row: LoginLog) => {
  currentLog.value = row
  detailVisible.value = true
}

// 关闭详情
const handleCloseDetail = () => {
  detailVisible.value = false
  currentLog.value = {} as LoginLog
}

// 选择变化
const handleSelectionChange = (selection: LoginLog[]) => {
  selectedLogs.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchLoginLogList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchLoginLogList()
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dateTime
}

// 格式化时长
const formatDuration = (seconds: number) => {
  if (!seconds) return '-'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (minutes > 0) {
    return `${minutes}分钟${secs}秒`
  } else {
    return `${secs}秒`
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLoginLogList()
  getStatistics()
})
</script>

<style scoped>
.login-log-container {
  padding: 20px;
}

.log-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  text-align: center;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.statistics-item {
  padding: 20px;
}

.statistics-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.statistics-number.success {
  color: #67c23a;
}

.statistics-number.danger {
  color: #f56c6c;
}

.statistics-number.warning {
  color: #e6a23c;
}

.statistics-label {
  font-size: 14px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.log-detail-pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
}
</style> 